"""
FIVEDASH(TM) -- General Purpose Accounting Software
Copyright (C) 2008  Obol Software Pty Ltd

This program is free software: you can redistribute it and/or modify
it. For terms and conditions, see fivedash/license/license.txt

"""

import os
import smtplib
import mimetypes
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.mime.audio import MIMEAudio
from email.mime.image import MIMEImage
from email.Utils import COMMASPACE, formatdate
from email import Encoders

from phunc.logger import logger
from phunc.error import genErrorPage,showErr
'''
	function:
			send email
	parameter:
			send_from = 'from@test.com'	#the email send from address
			send_to = ['to@test.com']		#the email send to address 
			subject = 'test'							#the email subject
			text = 'hello,this is a test'			#the email content
			files = ['test.txt']						#email attachment
			server = 'stmp.test.com'			#send email server			
			auth_required = 0   					#if you need to use SMTP AUTH set to 1
			smtpuser = 'liangtianyou' 		#for SMTP AUTH, set SMTP username here
			smtppass = '******'  				#for SMTP AUTH, set SMTP password here
'''
def send_mail(send_from='liangtianyou@obolsoftware.com', send_to=['liangtianyou@obolsoftware.com'], subject='test',text='Hello,world', files=[],server="mail.obolsoftware.com",auth_required=0,smtp_user='',smtp_pass=''):
		msg = MIMEMultipart()
		msg['From'] = send_from
		msg['To'] = COMMASPACE.join(send_to)
		msg['Date'] = formatdate(localtime=True)
		msg['Subject'] = subject
		
		msg.attach( MIMEText(text) )
		
		if files:
				for file in files:
						try:
								ctype, encoding = mimetypes.guess_type(file)
								if ctype is None or encoding is not None:
										# No guess could be made, or the file is encoded (compressed), so
										# use a generic bag-of-bits type.
										ctype = 'application/octet-stream'
								maintype, subtype = ctype.split('/', 1)
								if maintype == 'text':
										fp = open(file)
										# Note: we should handle calculating the charset
										part = MIMEText(fp.read(), _subtype=subtype)
										fp.close()
								elif maintype == 'image':
										fp = open(file, 'rb')
										part = MIMEImage(fp.read(), _subtype=subtype)
										fp.close()
								elif maintype == 'audio':
										fp = open(file, 'rb')
										part = MIMEAudio(fp.read(), _subtype=subtype)
										fp.close()
								else:
										fp = open(file, 'rb')
										part = MIMEBase(maintype, subtype)
										part.set_payload(fp.read())
										fp.close()
										# Encode the payload using Base64
										Encoders.encode_base64(part)
								# Set the filename parameter
								part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
								msg.attach(part)
						except Exception,e:
								errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
								errmsg = errmsg.replace('<','').replace('>','').replace('.__str__','')
								logger.debug(errmsg)
		smtp = smtplib.SMTP(server)
		if auth_required:
				result = smtp.login(smtp_user, smtp_pass)						
		smtp.sendmail(send_from, send_to, msg.as_string())
		return
##		except Exception,e:
##				errmsg = "%s" % e.__str__ + ' : ' + ','.join([str(arg) for arg in e.args])
##				errmsg = errmsg.replace('<','').replace('>','').replace('.__str__','')
##				logger.debug(errmsg)
if __name__=='__main__':
		send_mail()
